//
//  HomeViewController.m
//  Assistant
//
//  Created by Hunk on 12-2-25.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "HomeViewController.h"
#import "AddressBookManager.h"
#import "GroupMembersViewController.h"
#import "AboutViewController.h"
#import <QuartzCore/QuartzCore.h>

#define TAG_QQVIEW (11)

@interface HomeViewController (Private)

- (void)resetGroupsArray;

@end

@implementation HomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    SAFE_RELEASE(_groupsArray)
    SAFE_RELEASE(_abPersonViewController)
    
    [super dealloc];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [_groupsArray removeAllObjects];
    [_groupsArray addObjectsFromArray:[[AddressBookManager sharedManager] addressBookGroups]];
    
    QQView *qqView = (QQView *)[self.view viewWithTag:TAG_QQVIEW];
    [qqView reloadQQView];
}

#pragma mark - View lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = NSLocalizedString(@"我的群组", nil);
    self.navigationController.navigationBar.tintColor = TINT_COLOR;

    // BackgroundImageView
    UIImageView *backgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 416.0)];
    [backgroundImageView setImage:[UIImage imageNamed:@"background.png"]];
    [self.view addSubview:backgroundImageView];
    [backgroundImageView release];
    
    // Init
    _groupsArray      = [[NSMutableArray alloc] init];
    
    // Init ABPersonViewController
    _abPersonViewController = [[ABPersonViewController alloc] init];
    [_abPersonViewController setAllowsEditing:YES];
    [_abPersonViewController setAllowsActions:YES];

    // LeftBarButtonItem
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"关于", nil)
                                                                          style:UIBarButtonItemStyleBordered
                                                                         target:self
                                                                         action:@selector(aboutButtonHandle:)];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    [leftBarButtonItem release];

//    UIButton *button = [UIButton buttonWithType:UIButtonTypeInfoLight];
//    [button setFrame:CGRectMake(0.0, 0.0, 40.0, 40.0)];
//    [button addTarget:self action:@selector(aboutButtonHandle:) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
//    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
//    [leftBarButtonItem release];
    
    // RightBarButtonItem
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(rightBarButtonHandle:)];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    [rightBarButtonItem release];
    
    // QQView
    QQView *qqView = [[QQView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 416.0)];
    [qqView setBackgroundColor:[UIColor clearColor]];
    [qqView setDataSource:self];
    [qqView setDelegate:self];
    [qqView setTag:TAG_QQVIEW];
    [self.view addSubview:qqView];
    [qqView release];
    
    // CoverImageView
    _coverImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 480)];
    [_coverImageView setBackgroundColor:[UIColor blackColor]];
    [_coverImageView setImage:[UIImage imageNamed:@"Default.png"]];
    [_coverImageView setAlpha:1.0];
    [[UIApplication sharedApplication].keyWindow addSubview:_coverImageView];
    
    [self performSelector:@selector(coverViewAnimationHandle:) withObject:nil afterDelay:0.0f];
}

- (void)coverViewAnimationHandle:(id)sender
{
    [UIView animateWithDuration:1.5
                     animations:^{
                         _coverImageView.alpha = 0.0;
                     } 
                     completion:^(BOOL finished) {
                         [_coverImageView removeFromSuperview];
                     }];
    /*
    CATransition *animation = [CATransition animation];
    animation.delegate = self;
    animation.duration = 1.0;//0.5f * slider.value;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    //	animation.fillMode = kCAFillModeBackwards;
    //	animation.endProgress = 1;//;slider.value;
    animation.removedOnCompletion = YES;
    animation.subtype = kCATransitionFromBottom;
    
    animation.type = @"cube";

     UIButton *theButton = (UIButton *)sender;
     
     switch (theButton.tag) {
     case 0:
     animation.type = @"cube";//---
     break;
     case 1:
     animation.type = @"suckEffect";//103
     break;
     case 2:
     animation.type = @"oglFlip";//When subType is "fromLeft" or "fromRight", it's the official one.
     break;
     case 3:
     animation.type = @"rippleEffect";//110
     break;
     case 4:
     animation.type = @"pageCurl";//101
     break;
     case 5:
     animation.type = @"pageUnCurl";//102
     break;
     case 6:
     animation.type = @"cameraIrisHollowOpen ";//107
     break;
     case 7:
     animation.type = @"cameraIrisHollowClose ";//106
     break;
     default:
     break;
     }
    
    [_backgroundImageView.layer addAnimation:animation forKey:@"animation"];
    */
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{    
    [UIView animateWithDuration:1.0
                     animations:^{
                         _coverImageView.alpha = 0.0;
                     } 
                     completion:^(BOOL finished) {
                         [_coverImageView removeFromSuperview];
                     }];
}

#pragma mark -
#pragma mark QQView Delegate & Datasource Methods
- (NSInteger)numberOfSectionsInQQView:(QQView *)qqView
{
    if(_groupsArray)
    {
        return [_groupsArray count];
    }
    return 0;
}

- (NSInteger)qqView:(QQView *)qqView numberOfRowsInSection:(NSInteger)section flag:(BOOL)flag
{   
    AddressBookGroup *addressBookGroup = [_groupsArray objectAtIndex:section];
    
    if(flag)
    {   
        return [addressBookGroup groupMembersCount];//[[addressBookGroup groupMembers] count];
    }
    else
    {   
        return 0;
    }
}

- (UIView *)qqView:(QQView *)qqView viewForHeaderInSection:(NSInteger)section
{
    /*
    // Get group members
    AddressBookGroup *addressBookGroup = [_groupsArray objectAtIndex:section];
    NSArray *groupMembers = [addressBookGroup groupMembers];
    
    // Header view
    UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320, 60.0)] autorelease];
    [headerView setBackgroundColor:[UIColor whiteColor]];
    
    // Group name label
    UILabel *groupNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(30.0, 0.0, 220, 60.0)];
    [groupNameLabel setBackgroundColor:[UIColor clearColor]];
    [groupNameLabel setFont:[UIFont systemFontOfSize:20]];
    [groupNameLabel setText:[[addressBookGroup groupName] stringByAppendingFormat:@"(%d)", [groupMembers count]]];
    [headerView addSubview:groupNameLabel];
    [groupNameLabel release];
    
    // Arrow view
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10.0, 25.0, 10.0, 10.0)];
    [imageView setBackgroundColor:[UIColor clearColor]];
    [imageView setImage:[UIImage imageNamed:@"next.png"]];
    
    BOOL bFold = [qqView headerViewFoldInSection:section];
    if(bFold && addressBookGroup.hasMember)
    {
        CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI / 2);
        
        [imageView setTransform:transform];
    }
    else
    {}
    
    [headerView addSubview:imageView];
    [imageView release];
    */
    
    // Get group members
    AddressBookGroup *addressBookGroup = [_groupsArray objectAtIndex:section];
    
    // Header view
    UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320, 60.0)] autorelease];
    [headerView setBackgroundColor:[UIColor clearColor]];
    
    // Background image view
    UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320, 60.0)];
    [bgImageView setBackgroundColor:[UIColor clearColor]];
    [bgImageView setImage:[UIImage imageNamed:@"cell_background.png"]];
    [headerView addSubview:bgImageView];
    [bgImageView release];
    
    // Group name label
    UILabel *groupNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(30.0, 0.0, 220, 60.0)];
    [groupNameLabel setBackgroundColor:[UIColor clearColor]];
    [groupNameLabel setFont:[UIFont systemFontOfSize:20]];
    [groupNameLabel setText:[[addressBookGroup groupName] stringByAppendingFormat:@"(%d)", [addressBookGroup groupMembersCount]]];
    [headerView addSubview:groupNameLabel];
    [groupNameLabel release];
    
    // Arrow view
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10.0, 25.0, 10.0, 10.0)];
    [imageView setBackgroundColor:[UIColor clearColor]];
    [imageView setImage:[UIImage imageNamed:@"next.png"]];
    
    BOOL bFold = [qqView headerViewFoldInSection:section];
    if(bFold && addressBookGroup.hasMember)
    {
        CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI / 2);
        
        [imageView setTransform:transform];
    }
    else
    {}
    
    [headerView addSubview:imageView];
    [imageView release];
    
    // Disclosure button
    UIButton *_button = [UIButton buttonWithType:UIButtonTypeCustom];
    [_button setBackgroundColor:[UIColor clearColor]];
    [_button setFrame:CGRectMake(250.0, 0.0, 310.0, 60.0)];
    [_button addTarget:self action:@selector(buttonHandle:) forControlEvents:UIControlEventTouchUpInside];
    [_button setTag:section];
    [headerView addSubview:_button];
    
    UIButton *disclosureButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    [disclosureButton setBackgroundColor:[UIColor clearColor]];
    [disclosureButton setFrame:CGRectMake(270.0, (60.0 - 30.0) / 2.0, 30.0, 30.0)];
    [disclosureButton setTag:section];
    [disclosureButton addTarget:self action:@selector(buttonHandle:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:disclosureButton];
    
    // Line view
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 59.0, 320, 1.0)];
    [lineView setBackgroundColor:[UIColor grayColor]];
    [headerView addSubview:lineView];
    [lineView release];
    
    return headerView;
}

- (UITableViewCell *)qqView:(QQView *)qqView 
                  tableView:(UITableView *)tableView 
      cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
    
    QQViewCell *cell = (QQViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if(cell == nil)
    {
        cell = [[[QQViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                  reuseIdentifier:cellIdentifier] autorelease];
        
        [cell setSelectionStyle:UITableViewCellSelectionStyleBlue];
        [cell setDelegate:self];
    }
    
    AddressBookGroup *addressBookGroup = [_groupsArray objectAtIndex:indexPath.section];
    AddressBookPerson *person = [[addressBookGroup groupMembers] objectAtIndex:indexPath.row];
    [cell setAddressBookPerson:person];
    
    return cell;
}

- (CGFloat)qqView:(QQView *)qqView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60.0;
}

- (CGFloat)qqView:(QQView *)qqView heightForHeaderInSection:(NSInteger)section
{
    return 60.0;
}

#ifdef REFRESH_TABLE_HEADER
- (void)pullToAddNewGroup:(QQView *)qqView
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"添加群组", nil)
                                                        message:@"\n\n" 
                                                       delegate:nil 
                                              cancelButtonTitle:NSLocalizedString(@"取消", nil)
                                              otherButtonTitles:NSLocalizedString(@"确定", nil), nil];
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 55.0, 260.0, 26.0)];
    [textField setBackgroundColor:[UIColor whiteColor]];
    [textField becomeFirstResponder];
    [textField setFont:[UIFont systemFontOfSize:20.0]];
    [textField setTextColor:[UIColor blackColor]];
    [textField setClearButtonMode:UITextFieldViewModeWhileEditing];
    [textField setPlaceholder:NSLocalizedString(@"新群组名", nil)];
    [textField setTag:2012];
    [alertView addSubview:textField];
    [textField release];
    
    [alertView setDelegate:self];
    [alertView show];
    [alertView release];
}
#endif

#pragma mark -
#pragma mark rightBarButtonHandle
- (void)rightBarButtonHandle:(id)sender
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"添加群组", nil)
                                                        message:@"\n\n" 
                                                       delegate:nil 
                                              cancelButtonTitle:NSLocalizedString(@"取消", nil)
                                              otherButtonTitles:NSLocalizedString(@"确定", nil), nil];
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 55.0, 260.0, 26.0)];
    [textField setBackgroundColor:[UIColor whiteColor]];
    [textField becomeFirstResponder];
    [textField setFont:[UIFont systemFontOfSize:20.0]];
    [textField setTextColor:[UIColor blackColor]];
    [textField setClearButtonMode:UITextFieldViewModeWhileEditing];
    [textField setPlaceholder:NSLocalizedString(@"新群组名", nil)];
    [textField setTag:2012];
    [alertView addSubview:textField];
    [textField release];
    
    [alertView setDelegate:self];
    [alertView show];
    [alertView release];
}

#pragma mark -
#pragma mark aboutButtonHandle
- (void)aboutButtonHandle:(id)sender
{
    AboutViewController *aboutViewController = [[AboutViewController alloc] init];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:aboutViewController];
    [aboutViewController release];
    [self presentModalViewController:navigationController animated:YES];
    [navigationController release];
}

#pragma mark -
#pragma mark UIAlertView Delegate Method
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{   
    // 确定添加群组
    if(1 == buttonIndex)
    {
        UITextField *textField = (UITextField *)[alertView viewWithTag:2012];
        
        // Get input
        if([[AddressBookManager sharedManager] addNewGroupWith:textField.text])
        {
            [_groupsArray removeAllObjects];
            [_groupsArray addObjectsFromArray:[[AddressBookManager sharedManager] addressBookGroups]];
            
            QQView *qqView = (QQView *)[self.view viewWithTag:TAG_QQVIEW];
            [qqView reloadQQView];
        }
        else
        {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"添加群组失败", nil) 
                                                                message:nil
                                                               delegate:nil
                                                      cancelButtonTitle:NSLocalizedString(@"好的", nil)
                                                      otherButtonTitles:nil];
            [alertView show];
            [alertView release];
        }
    }
}

#pragma mark -
#pragma mark QQViewCell Delegate Method
- (void)QQViewCell:(QQViewCell *)cell didSelected:(AddressBookPerson *)addressBookPerson
{    
    _abPersonViewController.displayedPerson = [addressBookPerson record];
    [self.navigationController pushViewController:_abPersonViewController animated:YES];
}

#pragma mark -
#pragma mark buttonHandle
- (void)buttonHandle:(id)sender
{
    UIButton *button = (UIButton *)sender;
    
    AddressBookGroup *addressBookGroup = [_groupsArray objectAtIndex:[button tag]];
    
    GroupMembersViewController *groupMembersViewController = [[GroupMembersViewController alloc] init];
    [groupMembersViewController setAddressBookGroup:addressBookGroup];
    [self.navigationController pushViewController:groupMembersViewController animated:YES];
    [groupMembersViewController release];
}

#pragma mark -
#pragma mark Others
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
